import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { LoginRequest, RegisterRequest, UserInfo, LoginResponse, RegisterResponse, UserInfoResponse } from '../types/auth'
import { login as apiLogin, register as apiRegister, logout as apiLogout, getCurrentUser as apiGetCurrentUser, sendResetPasswordEmail as apiSendResetPasswordEmail, validateToken as apiValidateToken, refreshToken as apiRefreshToken, getUserInfo as apiGetUserInfo, updateUserInfo as apiUpdateUserInfo, uploadAvatar as apiUploadAvatar } from '../api/auth'
import { ElMessage } from 'element-plus'
import router from '../router'
import axios from 'axios'

// 认证状态存储键名
const AUTH_STORAGE_KEY = 'auth_state'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string | null>(null)
  const user = ref<UserInfo | null>(null)
  const loading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.role === 'admin')

  // 重置store状态
  function reset() {
    token.value = null
    user.value = null
    loading.value = false
  }

  // 从localStorage加载用户信息
  function loadUserFromStorage() {
    const storedToken = localStorage.getItem('token')
    const storedUser = localStorage.getItem('user')
    
    if (storedToken && storedUser) {
      try {
        token.value = storedToken
        user.value = JSON.parse(storedUser)
      } catch (e) {
        console.error('加载用户信息失败', e)
        reset()
      }
    }
  }

  // 初始加载用户信息
  loadUserFromStorage()

  // 登录
  async function login(loginData: LoginRequest) {
    try {
      loading.value = true
      
      // 创建不包含remember字段的登录数据
      const apiLoginData = {
        username: loginData.username,
        password: loginData.password
      }
      
      // 显示原始登录数据和实际发送的数据（仅开发时使用）
      console.log('原始登录数据:', loginData)
      console.log('实际发送的登录数据:', apiLoginData)
      console.log('请求URL:', 'api/auth/login')
      
      // 调用API进行登录
      const response = await apiLogin(apiLoginData)
      
      console.log('登录API返回:', response)
      
      // 检查响应中是否包含数据
      if (response?.code === 200) {
        const authData = response.data
        
        console.log('解析的认证数据:', authData)
        
        // 确保有token
        if (!authData?.token) {
          console.error('认证数据中没有token')
          ElMessage.error('登录失败: 服务器响应中缺少token')
          return false
        }
        
        // 保存令牌
        token.value = authData.token
        localStorage.setItem('token', authData.token)
        
        // 从响应中直接获取用户信息
        const userInfo: UserInfo = {
          id: authData.openid || '0',
          username: authData.username || '',
          email: authData.email || '',
          avatar: authData.avatar || '',
          avatarUrl: authData.avatarUrl || '',
          nickname: authData.nickname || '',
          phone: authData.phone || '',
          role: authData.role || 'user'
        }
        
        // 保存用户信息
        user.value = userInfo
        localStorage.setItem('user', JSON.stringify(userInfo))
        console.log('已保存用户信息:', userInfo)
        
        // 记住我功能
        if (loginData.remember) {
          localStorage.setItem('rememberedUsername', loginData.username)
        } else {
          localStorage.removeItem('rememberedUsername')
        }
        
        ElMessage.success('登录成功')
        return true
      }
      
      ElMessage.error(response?.message || '登录失败: 服务器响应无效')
      return false
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请检查网络连接')
      return false
    } finally {
      loading.value = false
    }
  }

  // 注册
  async function register(registerData: RegisterRequest) {
    try {
      loading.value = true
      
      // 创建不包含confirmPassword和agreement字段的注册数据
      const apiRegisterData = {
        username: registerData.username,
        email: registerData.email,
        password: registerData.password
        // 移除confirmPassword和agreement字段
      }
      
      console.log('原始注册数据:', registerData)
      console.log('实际发送的注册数据:', apiRegisterData)
      
      const response = await apiRegister(apiRegisterData)
      
      console.log('注册响应:', response)
      
      if (response?.code === 200 && response.data) {
        const authData = response.data
        if (authData.token) {
          // 保存token
          token.value = authData.token
          localStorage.setItem('token', authData.token)
          
          // 从响应中直接获取用户信息
          const userInfo: UserInfo = {
            id: authData.openid || '0',
            username: authData.username || '',
            email: authData.email || '',
            avatar: authData.avatar || '',
            avatarUrl: authData.avatarUrl || '',
            nickname: authData.nickname || '',
            phone: authData.phone || '',
            role: authData.role || 'user'
          }
          
          // 保存用户信息
          user.value = userInfo
          localStorage.setItem('user', JSON.stringify(userInfo))
          console.log('已保存用户信息:', userInfo)
          
          // 注册成功消息已经在Register.vue中显示，这里不重复显示
          return true
        }
      }
      
      // 显示服务器返回的错误消息
      if (response?.message) {
        ElMessage.error(response.message)
      } else {
        ElMessage.error('注册失败，请稍后重试')
      }
      return false
    } catch (error: any) {
      console.error('注册失败:', error)
      
      // 处理可能的错误情况，只显示最具体的错误信息
      if (error.response && error.response.data && error.response.data.message) {
        // 显示服务器返回的错误消息
        ElMessage.error(error.response.data.message)
      } else if (error.response && error.response.status === 409) {
        // 409冲突，通常是用户名或邮箱已存在
        ElMessage.error('用户名或邮箱已被注册')
      } else if (error.response && error.response.status === 400) {
        // 400错误，通常是请求格式错误
        ElMessage.error('提交数据格式不正确')
      } else if (error.message) {
        // 显示错误对象的消息
        ElMessage.error(error.message)
      } else {
        // 通用错误
        ElMessage.error('注册失败，请检查网络连接')
      }
      return false
    } finally {
      loading.value = false
    }
  }

  // 登出
  async function logout() {
    try {
      loading.value = true
      await apiLogout()
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('rememberedUsername')
      
      // 重置状态
      reset()
      
      ElMessage.success('已退出登录')
      return true
    } catch (error) {
      console.error('登出失败:', error)
      ElMessage.error('登出失败，请重试')
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取当前用户信息
  async function getCurrentUser() {
    try {
      loading.value = true
      console.log('开始获取用户信息...')
      console.log('当前token:', localStorage.getItem('token'))
      
      const response = await apiGetCurrentUser()
      
      console.log('获取用户信息响应:', {
        code: response?.code,
        message: response?.message,
        data: response?.data,
        完整响应: response
      })
      
      if (response?.code === 200 && response.data) {
        user.value = response.data
        localStorage.setItem('user', JSON.stringify(response.data))
        console.log('已更新用户信息:', response.data)
        return true
      }
      
      console.error('获取用户信息失败: 响应格式不正确', {
        期望格式: {
          code: 200,
          message: "获取用户信息成功",
          data: {
            id: "用户ID",
            username: "用户名",
            // ...其他字段
          }
        },
        实际响应: response
      })
      return false
    } catch (error: any) {
      console.error('获取用户信息失败:', {
        错误信息: error?.message,
        响应数据: error?.response?.data,
        完整错误: error
      })
      return false
    } finally {
      loading.value = false
    }
  }

  // 检查应用状态
  const checkAppState = () => {
    // 返回认证状态和用户信息，但不输出日志
    return {
      authenticated: isAuthenticated.value,
      user: user.value,
      token: token.value,
      routes: router.getRoutes().map(r => ({ 
        name: r.name, 
        path: r.path,
        children: r.children?.length
      }))
    }
  }

  // 获取记住的用户名
  const getRememberedUsername = (): string => {
    return localStorage.getItem('rememberedUsername') || ''
  }

  // 刷新令牌
  const refreshToken = async (): Promise<boolean> => {
    try {
      const response = await apiRefreshToken()
      if (response && response.data) {
        token.value = response.data.token
        localStorage.setItem('token', response.data.token)
        return true
      }
      return false
    } catch (error) {
      console.error('刷新令牌失败:', error)
      return false
    }
  }

  // 发送重置密码邮件
  const sendResetPasswordEmail = async (email: string) => {
    try {
      loading.value = true
      await apiSendResetPasswordEmail({ email })
      ElMessage.success('重置密码邮件已发送')
      return true
    } catch (error) {
      console.error('发送重置密码邮件失败:', error)
      ElMessage.error('发送重置密码邮件失败，请重试')
      return false
    } finally {
      loading.value = false
    }
  }

  // 验证令牌
  const validateToken = async (tokenToValidate: string) => {
    try {
      const response = await apiValidateToken(tokenToValidate)
      return response.data.valid
    } catch (error) {
      console.error('令牌验证失败:', error)
      return false
    }
  }

  // 更新用户信息
  async function updateProfile(userData: Partial<UserInfo>) {
    try {
      loading.value = true
      
      if (!user.value?.id) {
        ElMessage.error('用户未登录')
        return false
      }
      
      console.log('开始更新用户信息:', userData)
      
      const response = await apiUpdateUserInfo(user.value.id, userData)
      
      console.log('更新用户信息响应:', response)
      
      if (response?.success && response.data) {
        // 更新本地用户信息
        user.value = response.data
        localStorage.setItem('user', JSON.stringify(response.data))
        
        ElMessage.success('个人信息更新成功')
        return true
      }
      
      ElMessage.error(response?.message || '更新失败')
      return false
    } catch (error) {
      console.error('更新用户信息失败:', error)
      ElMessage.error('更新失败，请重试')
      return false
    } finally {
      loading.value = false
    }
  }

  // 上传头像
  async function uploadAvatar(file: File) {
    try {
      loading.value = true
      
      // 检查文件类型
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
      if (!allowedTypes.includes(file.type)) {
        ElMessage.error('只支持JPG、PNG、GIF格式的图片')
        return false
      }
      
      // 检查文件大小（2MB）
      if (file.size > 2 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过2MB')
        return false
      }
      
      // 确保传递用户ID
      const userId = user.value?.id
      const response = await apiUploadAvatar(file, userId)
      
      // 适配新的API响应格式
      if (response?.code === 200 && response.data) {
        // 更新本地用户信息
        const userInfo: UserInfo = {
          id: response.data.openid || user.value?.id || '0',
          username: response.data.username || user.value?.username || '',
          email: response.data.email || user.value?.email || '',
          avatar: response.data.avatar || user.value?.avatar || '',
          avatarUrl: response.data.avatarUrl || user.value?.avatarUrl || '',
          nickname: response.data.nickname || user.value?.nickname || '',
          phone: response.data.phone || user.value?.phone || '',
          role: response.data.role || user.value?.role || 'user'
        }
        
        // 保存更新后的用户信息
        user.value = userInfo
        localStorage.setItem('user', JSON.stringify(userInfo))
        
        // 显示成功消息
        ElMessage.success('头像上传成功')
        return true
      }
      
      ElMessage.error(response?.message || '上传失败')
      return false
    } catch (error: any) {
      console.error('上传头像失败:', error)
      
      // 更详细的错误处理
      if (error.response && error.response.data && error.response.data.message) {
        ElMessage.error(error.response.data.message)
      } else if (error.message) {
        ElMessage.error(error.message)
      } else {
        ElMessage.error('上传失败，请重试')
      }
      return false
    } finally {
      loading.value = false
    }
  }

  return {
    token,
    user,
    loading,
    isAuthenticated,
    isAdmin,
    login,
    register,
    logout,
    getCurrentUser,
    checkAppState,
    getRememberedUsername,
    refreshToken,
    sendResetPasswordEmail,
    validateToken,
    loadUserFromStorage,
    updateProfile,
    uploadAvatar,
    $reset: reset
  }
}) 